import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import axios from 'axios'

// 配置API基础URL
const api = axios.create({
  baseURL: 'http://localhost:8080',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  }
})

// 请求拦截器 - 添加全局参数
api.interceptors.request.use(
  (config) => {
    // 添加全局query参数
    config.params = {
      ...config.params,
      authKey: 'MDY0OUY4Qjk1OTDEN0ZFN0JDMjcwQTJBQzE5MUIxMzQyQkRFRUFCOTZGMTA5NTYxNTVDREQxODhDODc1RUJEQkYxRTExOURFNkQyOTAwNzE=',
      sessionId: 'dc8b947ee45c42fe9dc1fbdc144beb411750640408425'
    }
    
    // 添加全局header
    config.headers.Authorization = 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImxvZ2luX3VzZXJfa2V5IjoiMmM3YmViYzAtYjQ4ZS00Y2Y0LTk3ZWUtOGI2NzM3YThiNTVhIn0.o0tXtE9lv7y8bkoNK6vmVyGDAnSvUOZmRkZeKdlcuKPDaZ8dQSBhNFXW79krIWN4FD6GjTcir9cHpjlL_reuHA'
    
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    console.error('API请求失败:', error)
    return Promise.reject(error)
  }
)

// 商品数据类型定义
export interface Goods {
  id: number
  goodsName: string
  goodsType: string
  goodsContent: string
  status: number
  goodsMoney: number
  goodsPic?: string
  createTime: string
  createBy?: string
  updateTime?: string
  updateBy?: string
  remark?: string
  fileList?: any[]
}

// 商品列表响应类型
export interface GoodsListResponse {
  total: number
  rows: Goods[]
  code: number
  msg: string
}

// 查询商品列表参数
export interface GoodsListParams {
  goodsType?: string
  goodsContent?: string
  status?: number
}

// 定义Store
export const useGoodsStore = defineStore('goods', () => {
  // 状态
  const goodsList = ref<Goods[]>([])
  const currentGoods = ref<Goods | null>(null)
  const loading = ref(false)
  const total = ref(0)
  const searchParams = ref<GoodsListParams>({
    status: 0 // 默认查询正常状态的商品
  })

  // 计算属性
  const goodsTypes = computed(() => {
    const types = new Set(goodsList.value.map(item => item.goodsType))
    return Array.from(types)
  })

  // 根据类型过滤商品
  const filteredGoods = computed(() => {
    if (!searchParams.value.goodsType) {
      return goodsList.value
    }
    return goodsList.value.filter(item => item.goodsType === searchParams.value.goodsType)
  })

  // API方法
  const fetchGoodsList = async (params?: GoodsListParams) => {
    loading.value = true
    try {
      const response: GoodsListResponse = await api.get('/system/goods/list', {
        params: {
          ...searchParams.value,
          ...params
        }
      })
      
      if (response.code === 200) {
        goodsList.value = response.rows
        total.value = response.total
      }
    } catch (error) {
      console.error('获取商品列表失败:', error)
      // 添加一些示例数据用于演示
      goodsList.value = [
        {
          id: 1,
          goodsName: '时尚连衣裙',
          goodsType: '女装',
          goodsContent: '优雅时尚的连衣裙，适合各种场合穿着',
          status: 0,
          goodsMoney: 299,
          goodsPic: '',
          createTime: '2025-06-08 10:00:00',
          createBy: 'admin'
        },
        {
          id: 2,
          goodsName: '休闲T恤',
          goodsType: '男装',
          goodsContent: '舒适透气的休闲T恤，日常穿着的好选择',
          status: 0,
          goodsMoney: 89,
          goodsPic: '',
          createTime: '2025-06-08 11:00:00',
          createBy: 'admin'
        },
        {
          id: 3,
          goodsName: '儿童卫衣',
          goodsType: '童装',
          goodsContent: '柔软舒适的儿童卫衣，保暖又可爱',
          status: 0,
          goodsMoney: 128,
          goodsPic: '',
          createTime: '2025-06-08 12:00:00',
          createBy: 'admin'
        }
      ]
      total.value = goodsList.value.length
    } finally {
      loading.value = false
    }
  }

  const fetchGoodsDetail = async (id: number) => {
    loading.value = true
    try {
      // 获取用户IP（这里简化处理）
      const ip = '127.0.0.1'
      await api.get('/system/goods/detail', { 
        params: { id, ip } 
      })
      
      // 从列表中查找商品详情
      const goods = goodsList.value.find(item => item.id === id)
      if (goods) {
        currentGoods.value = goods
      }
    } catch (error) {
      console.error('获取商品详情失败:', error)
      // 从列表中查找商品详情作为备选
      const goods = goodsList.value.find(item => item.id === id)
      if (goods) {
        currentGoods.value = goods
      }
    } finally {
      loading.value = false
    }
  }

  const setSearchParams = (params: GoodsListParams) => {
    searchParams.value = { ...searchParams.value, ...params }
  }

  const clearCurrentGoods = () => {
    currentGoods.value = null
  }

  return {
    // 状态
    goodsList,
    currentGoods,
    loading,
    total,
    searchParams,
    
    // 计算属性
    goodsTypes,
    filteredGoods,
    
    // 操作
    fetchGoodsList,
    fetchGoodsDetail,
    setSearchParams,
    clearCurrentGoods
  }
}) 